import { expect } from 'chai';
import * as sinon from 'sinon';
import { SetSSHPrivateKey } from '../src/sshKey';
import * as fs from 'fs' // 调整路径以匹配你的文件位置


const workDir = './workspace';

describe('SetSSHPrivateKey', () => {

    let envStub: sinon.SinonStub;

    beforeEach(() => {
        envStub = sinon.stub(process, 'env');
        if (!fs.existsSync(workDir)){
            fs.mkdirSync(workDir);
        }
    });

    afterEach(() => {
        envStub.restore();
    });

    it('should set SSH private key for the repo', () => {
        const repoDirName = 'my-repo_LBTL';
        const sources = JSON.stringify([
            {
                name: 'irrelevant——repo-0',
                data: {
                    sshPrivateKey: 'irrelevant_private-0',
                },
            },
            {
                name: 'irrelevant——repo-http',
                data: {
                    method: 'http'
                },
            },
            {
                name: 'my-repo_LBTL',
                data: {
                    sshPrivateKey: 'private-key3',
                },
            },
            {
                name: 'irrelevant——repo',
                data: {
                    sshPrivateKey: 'irrelevant_private',
                },
            },
        ]);

        envStub.value({'WORK_SPACE': workDir,'SOURCES': sources});
        SetSSHPrivateKey(repoDirName);

        let expectedPK = fs.readFileSync(`${workDir}/.ssh/id_rsa`).toString()
        expect(expectedPK).to.equal('private-key3')
        expect(process.env.GIT_SSH_COMMAND).to.equal(`ssh -i '${workDir}/.ssh/id_rsa' -o StrictHostKeyChecking=no`);
    });

    it('should not set SSH private key if connection method is not ssh', () => {
        const repoDirName = 'my-repo-2_DERG';
        const sources = JSON.stringify([
            {
                name: 'irrelevant——repo-0',
                data: {
                    sshPrivateKey: 'irrelevant_private-0',
                },
            },
            {
                name: 'my-repo-2_DERG',
                data: {
                    method: 'http',
                },
            },
            {
                name: 'irrelevant——repo-1',
                data: {
                    sshPrivateKey: 'irrelevant_private-0',
                },
            },
        ]);
        envStub.value({'WORK_SPACE': workDir,'SOURCES': sources});
        SetSSHPrivateKey(repoDirName);

        expect(process.env.GIT_SSH_COMMAND).to.be.undefined;
    });
});